﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QLNHK.BLL;
using System.Threading;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win.Misc;

namespace QLNHK
{
    public partial class frmThemMoiHoKhau : FrmBase
    {
        private HoKhau _objHoKhau;
        public HoKhau ObjHoKhau
        {
            get { return _objHoKhau; }
            set { _objHoKhau = value; }
        }
        frmWait frmWaiting;
        private List<NhanKhau> _collectionsNhanKhau = new List<NhanKhau>();
        private NhanKhau _objChuHo;

        #region Set Authentication On Form
        private cls_Role ObjRole = null;
        private Cls_PHANQUYEN_NHOM ObjPhanQuyen = null;
        private Infragistics.Win.DefaultableBoolean GetStatus(bool values)
        {
            if (values)
            {
                return Infragistics.Win.DefaultableBoolean.True;
            }
            else
            {
                return Infragistics.Win.DefaultableBoolean.False;
            }
        }
        private void SetAuthenticationOnForm()
        {
            try
            {
                if (!frmMain.ObjNguoiDung.IsAdministrator)
                {
                    ObjRole = new cls_Role();
                    ObjPhanQuyen = new Cls_PHANQUYEN_NHOM();

                    ObjRole = new cls_Role(Global.GetRole(ObjPhanQuyen.GetRoleByIDChucNang(frmMain.ObjNguoiDung.ID_NguoiDung, this.Tag.ToString())));

                    if (ObjRole != null)
                    {
                        if (ObjRole.HienThi == false)//không hiển thị
                        {
                            foreach (Control ctl in this.Controls)
                            {
                                ctl.Visible = false;
                            }
                        }
                        //chỉ cho phép hiển thị, không cho phép cập nhật, sửa, xóa
                        else if (ObjRole.HienThi == true && ObjRole.Them == false && ObjRole.Sua == false && ObjRole.Xoa == false)
                        {
                            //Grid
                            gridNhanKhau.DisplayLayout.Bands[0].Override.AllowDelete = GetStatus(ObjRole.Xoa);
                            gridNhanKhau.DisplayLayout.Bands[0].Override.AllowUpdate = GetStatus(ObjRole.Sua);
                            if (ObjRole.Them)
                                gridNhanKhau.DisplayLayout.Bands[0].Override.AllowAddNew = AllowAddNew.TemplateOnTopWithTabRepeat;

                            btnLuu.Enabled = (ObjRole.Them || ObjRole.Sua);
                        }
                        //cho phép hiển thị, cho phép hoặc cập nhật, hoặc sửa, hoặc xóa
                        else
                        {
                            CheckAuthentication();
                        }
                    }
                }

                btnDong.Enabled = true;
            }

            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
            }
        }
        private void CheckAuthentication()
        {
            try
            {
                if (ObjRole != null)
                {
                    //chỉ hiển thị và thêm mới
                    if (ObjRole.Them == true && ObjRole.Sua == false && ObjRole.Xoa == false)
                    {
                        gridNhanKhau.DisplayLayout.Override.AllowDelete = DefaultableBoolean.False;
                        //btnXoa.Enabled = false;

                        foreach (UltraGridRow ugRow in gridNhanKhau.Rows)
                        {
                            ugRow.Activation = Activation.NoEdit;
                        }
                    }
                    //chỉ hiển thị và sửa
                    else if (ObjRole.Them == false && ObjRole.Sua == true && ObjRole.Xoa == false)
                    {
                        gridNhanKhau.DisplayLayout.Override.AllowAddNew = AllowAddNew.No;
                        gridNhanKhau.DisplayLayout.Override.AllowUpdate = DefaultableBoolean.True;
                        gridNhanKhau.DisplayLayout.Override.AllowDelete = DefaultableBoolean.False;
                        //btnXoa.Enabled = false;
                    }
                    //chỉ hiển thị và xóa
                    else if (ObjRole.Them == false && ObjRole.Sua == false && ObjRole.Xoa == true)
                    {
                        gridNhanKhau.DisplayLayout.Override.AllowAddNew = AllowAddNew.No;
                        gridNhanKhau.DisplayLayout.Override.AllowUpdate = DefaultableBoolean.False;
                        gridNhanKhau.DisplayLayout.Override.AllowDelete = DefaultableBoolean.True;
                        //btnXoa.Enabled = true;
                    }
                    //chỉ hiển thị và thêm mới, sửa
                    else if (ObjRole.Them == true && ObjRole.Sua == true && ObjRole.Xoa == false)
                    {
                        gridNhanKhau.DisplayLayout.Override.AllowDelete = DefaultableBoolean.False;
                        //btnXoa.Enabled = false;
                    }
                    //chỉ hiển thị và thêm mới, xóa
                    else if (ObjRole.Them == true && ObjRole.Sua == false && ObjRole.Xoa == true)
                    {
                        gridNhanKhau.DisplayLayout.Override.AllowDelete = DefaultableBoolean.True;
                        //btnXoa.Enabled = true;
                        foreach (UltraGridRow ugRow in gridNhanKhau.Rows)
                        {
                            ugRow.Activation = Activation.NoEdit;
                        }
                    }
                    //chỉ hiển thị và sửa, xóa
                    else if (ObjRole.Them == false && ObjRole.Sua == true && ObjRole.Xoa == true)
                    {
                        gridNhanKhau.DisplayLayout.Override.AllowDelete = DefaultableBoolean.True;
                        //btnXoa.Enabled = true;
                    }
                    //chỉ hiển thị và thêm mới, sửa, xóa: đã được xử lý trong method SetAuthenticationOnForm()
                }
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
            }
        }
        #endregion

        public frmThemMoiHoKhau()
        {
            InitializeComponent();
        }
        private void frmThemMoiHoKhau_Load(object sender, EventArgs e)
        {
            ddbChuyenDi.PopupItem = ultraPopupControlContainer1;

            frmWaiting = new frmWait();
            ThreadPool.QueueUserWorkItem(OnProcess);
            frmWaiting.SetCaption("Vui lòng chờ giây lát");
            frmWaiting.ShowDialog(this);
        }
        private void OnProcess(object o)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate
                {
                    if (ObjHoKhau == null)
                    {
                        this.Text = "Thêm mới hộ khẩu";
                        //Thiet lap du lieu mac dinh
                        ResetData(ref frmWaiting);
                    }
                    else
                    {
                        this.Text = "Chỉnh sửa hộ khẩu";
                        ResetData(ref frmWaiting);
                        //Nap du lieu
                        LoadData(ref frmWaiting);
                    }

                    frmWaiting.DialogResult = DialogResult.OK;
                    Show();
                }));
            }
        }

        private void ResetData(ref frmWait frmW)
        {
            try
            {
                frmW.SetCaption("Đang tạo dữ liệu mặc định...");

                errorProvider1.Clear();

                //Ho khau
                Global.setDataToComboDanhMuc(cboLoaiHoKhau, DMCatalogue.DM_LOAIHOKHAU);
                txtSoSoHK.Text = txtHoSoHKSo.Text = txtDiaChi.Text = txtChiBo.Text = txtGhiChu.Text = string.Empty;
                Global.setDataToComboThanhPho(cboThanhPho); cboThanhPho.Value = ConfigNHK.Install.ThanhPho; // Global.DIABAN_THANHPHO;
                Global.setDataToComboQuanHuyen(cboQuanHuyen, (int)cboThanhPho.Value);
                Global.setDataToComboXaPhuong(cboXaPhuong, (int)cboQuanHuyen.Value);
                Global.setDataToComboToDanPho(cboToDanPho, (int)cboXaPhuong.Value);

                //Nhan khau
                txtHoLot.Text = txtTen.Text = txtCMND.Text = txtDienThoai.Text = txtNgheNghiep.Text = string.Empty;
                Global.setDataToComboNgaySinh(cboNgaySinh);
                Global.setDataToComboThangSinh(cboThangSinh);
                Global.setDataToComboNamSinh(cboNamSinh);
                optGioiTinh.CheckedIndex = 0; //0: Nu; 1: Nam; 2: Khong xac dinh

                Global.setDataToComboDanhMuc(cboDanToc, DMCatalogue.DM_DANTOC);
                Global.setDataToComboDanhMuc(cboQuocTich, DMCatalogue.DM_QUOCTICH);
                Global.setDataToComboThanhPho(cboThanhPhoChuHo); cboThanhPhoChuHo.Value = ConfigNHK.Install.ThanhPho; // Global.DIABAN_THANHPHO;
                Global.setDataToComboQuanHuyen(cboQuanHuyenChuHo, (int)cboThanhPhoChuHo.Value);
                Global.setDataToComboXaPhuong(cboXaPhuongChuHo, (int)cboQuanHuyenChuHo.Value);
                Global.setDataToComboToDanPho(cboToDanPhoChuHo, (int)cboXaPhuongChuHo.Value);

                cboLoaiHoKhau.Focus();

                //Load du lieu mac dinh cho grid
                LoadDataDanhSachNhanKhau(0);

                tabMain.Tabs[0].Selected = true;
            }
            catch (Exception ex) { Logger.LocalLogger.Instance().WriteMessage(ex); }
        }
        private void LoadData(ref frmWait frmW)
        {
            try
            {
                if (ObjHoKhau == null || ObjHoKhau.ID == 0) return;

                frmW.SetCaption("Đang mở dữ liệu hộ khẩu...");

                //Ho khau
                cboLoaiHoKhau.Value = ObjHoKhau.LoaiHoKhauID;
                txtSoSoHK.Text = ObjHoKhau.SoSoHoKhau.ToString("");
                txtHoSoHKSo.Text = ObjHoKhau.HSHKSo.ToString();
                txtChiBo.Text = ObjHoKhau.ChiBo;
                txtGhiChu.Text = ObjHoKhau.GhiChu;
                Global.setDataToComboThanhPho(cboThanhPho);
                txtDiaChi.Text = ObjHoKhau.DiaChi;
                cboThanhPho.Value = ObjHoKhau.TinhTPID;
                cboQuanHuyen.Value = ObjHoKhau.QuanHuyenID;
                cboXaPhuong.Value = ObjHoKhau.PhuongXaID;
                cboToDanPho.Value = ObjHoKhau.ToDanPhoID;

                //Nhan khau
                _collectionsNhanKhau = NhanKhau.SelectCollectionBy_HoKhauID(ObjHoKhau.ID);
                if (_collectionsNhanKhau.Count > 0)
                    _objChuHo = _collectionsNhanKhau.Find(delegate(NhanKhau nk)
                    {
                        if (nk.LaChuHo)
                            return true;

                        return false;
                    });

                if (_objChuHo != null)
                {
                    txtHoLot.Text = _objChuHo.HoLot;
                    txtTen.Text = _objChuHo.Ten;

                    cboNgaySinh.Value = _objChuHo.NgaySinh;
                    cboThangSinh.Value = _objChuHo.ThangSinh;
                    cboNamSinh.Value = _objChuHo.NamSinh;
                    optGioiTinh.Value = _objChuHo.GioiTinh;

                    //Que quan
                    Global.setDataToComboThanhPho(cboThanhPhoChuHo);
                    cboThanhPhoChuHo.Value = _objChuHo.QueQuanTinhTPID;
                    cboQuanHuyenChuHo.Value = _objChuHo.QueQuanQuanHuyenID;
                    cboXaPhuongChuHo.Value = _objChuHo.QueQuanXaPhuongID;
                    cboToDanPhoChuHo.Value = _objChuHo.QueQuanToID;

                    txtCMND.Text = _objChuHo.SoCMND;
                    cboDanToc.Value = _objChuHo.DanTocID;
                    cboQuocTich.Value = _objChuHo.QuocTichID;
                    txtDienThoai.Text = _objChuHo.SoDienThoaiLienHe;
                    txtNgheNghiep.Text = _objChuHo.NgheNghiepNoiLamViec;
                }

                cboLoaiHoKhau.Focus();

                //Load du lieu danh sach nhan khau
                LoadDataDanhSachNhanKhau(ObjHoKhau.ID);

                //Kiem tra phan quyen sau khi nap du lieu
                SetAuthenticationOnForm();
            }
            catch (Exception ex) { Logger.LocalLogger.Instance().WriteMessage(ex); }
        }
        private bool GetData()
        {
            bool isValid = false;
            try
            {
                if (ObjHoKhau == null)
                    ObjHoKhau = new HoKhau();

                if (!ValidateForm())
                    return (isValid = false);

                //Ho khau
                ObjHoKhau.LoaiHoKhauID = System.Convert.ToInt32(cboLoaiHoKhau.Value);
                ObjHoKhau.SoSoHoKhau = System.Convert.ToInt32(txtSoSoHK.Text.Trim());
                if (txtHoSoHKSo.Text.Trim().Length > 0)
                    ObjHoKhau.HSHKSo = System.Convert.ToInt32(txtHoSoHKSo.Text.Trim());

                ObjHoKhau.DiaChi = txtDiaChi.Text;
                ObjHoKhau.TinhTPID = System.Convert.ToInt32(cboThanhPho.Value);
                ObjHoKhau.QuanHuyenID = System.Convert.ToInt32(cboQuanHuyen.Value);
                ObjHoKhau.PhuongXaID = System.Convert.ToInt32(cboXaPhuong.Value);
                ObjHoKhau.ToDanPhoID = System.Convert.ToInt32(cboToDanPho.Value);

                ObjHoKhau.ChiBo = txtChiBo.Text;
                ObjHoKhau.GhiChu = txtGhiChu.Text;
                ObjHoKhau.CanBoQuanLyID = frmMain.ObjNguoiDung.ID_NguoiDung;

                isValid = true;
            }
            catch (Exception ex) { Logger.LocalLogger.Instance().WriteMessage(ex); }

            return isValid;
        }
        private void TaoThongTinChuHo()
        {
            //Nhan Khau
            if (_objChuHo == null)
                _objChuHo = new NhanKhau();

            //Neu ho khau tao moi thanh cong -> Tao thong tin chu ho
            if (_objHoKhau.ID > 0)
            {
                //Truong hop them moi nhan khau
                if (_objChuHo.ID == 0)
                {
                    //Ho khau
                    _objChuHo.HoKhauID = _objHoKhau != null ? _objHoKhau.ID : 0;
                    _objChuHo.LaChuHo = true;
                    _objChuHo.TinhTrang = System.Convert.ToInt32(ETinhTrang.DangCuTru);
                    _objChuHo.MaNhanKhau = NhanKhau.GetNewMaNhanKhau();
                }
            }
            else
                return;

            _objChuHo.HoLot = txtHoLot.Text.Trim();
            _objChuHo.Ten = txtTen.Text.Trim();

            _objChuHo.NgaySinh = System.Convert.ToInt32(cboNgaySinh.Value);
            _objChuHo.ThangSinh = System.Convert.ToInt32(cboThangSinh.Value);
            _objChuHo.NamSinh = System.Convert.ToInt32(cboNamSinh.Value);
            _objChuHo.GioiTinh = System.Convert.ToInt32(optGioiTinh.Value);

            //Que quan
            _objChuHo.QueQuanTinhTPID = System.Convert.ToInt32(cboThanhPhoChuHo.Value);
            _objChuHo.QueQuanQuanHuyenID = System.Convert.ToInt32(cboQuanHuyenChuHo.Value);
            _objChuHo.QueQuanXaPhuongID = System.Convert.ToInt32(cboXaPhuongChuHo.Value);
            _objChuHo.QueQuanToID = System.Convert.ToInt32(cboToDanPhoChuHo.Value);

            //Thuong tru
            _objChuHo.ThuongTruTinhTPID = System.Convert.ToInt32(cboThanhPho.Value);
            _objChuHo.ThuongTruQuanHuyenID = System.Convert.ToInt32(cboQuanHuyen.Value);
            _objChuHo.ThuongTruXaPhuongID = System.Convert.ToInt32(cboXaPhuong.Value);
            _objChuHo.ThuongTruToID = System.Convert.ToInt32(cboToDanPho.Value);
            _objChuHo.ThuongTruDiaChi = txtDiaChi.Text.Trim();

            _objChuHo.DanTocID = System.Convert.ToInt32(cboDanToc.Value);
            _objChuHo.QuocTichID = System.Convert.ToInt32(cboQuocTich.Value);

            _objChuHo.SoCMND = txtCMND.Text;

            _objChuHo.NgheNghiepNoiLamViec = txtNgheNghiep.Text;
            _objChuHo.SoDienThoaiLienHe = txtDienThoai.Text;

            //Luu thong tin
            if (_objChuHo.ID == 0)
                _objChuHo.Insert();
            else
                _objChuHo.Update();
        }
        private bool ValidateForm()
        {
            bool isValid = true;
            errorProvider1.Clear();

            try
            {
                //Ho khau
                isValid &= Validations_Infragistics.ValidateChoose(cboXaPhuong, errorProvider1, "Xã/ Phường chủ hộ");
                isValid &= Validations_Infragistics.ValidateChoose(cboQuanHuyen, errorProvider1, "Quận/ Huyện chủ hộ");
                isValid &= Validations_Infragistics.ValidateChoose(cboThanhPho, errorProvider1, "Tỉnh/ Thành phố chủ hộ");
                //isValid &= Validations_Infragistics.ValidateNull(txtDiaChi, errorProvider1, "Địa chỉ hộ khẩu");

                isValid &= Validations_Infragistics.ValidateNull(txtSoSoHK, errorProvider1, "Số sổ hộ khẩu");
                isValid &= Validations_Infragistics.ValidateChoose(cboLoaiHoKhau, errorProvider1, "Loại hộ khẩu");

                //Nhan khau
                isValid &= Validations_Infragistics.ValidateNull(txtNgheNghiep, errorProvider1, "Nghề nghiệp, nơi làm việc");

                isValid &= Validations_Infragistics.ValidateChoose(cboQuocTich, errorProvider1, "Tôn giáo");
                isValid &= Validations_Infragistics.ValidateChoose(cboDanToc, errorProvider1, "Dân tộc");

                isValid &= Validations_Infragistics.ValidateNull(txtCMND, errorProvider1, "Số CMND");

                isValid &= Validations_Infragistics.ValidateChoose(cboXaPhuongChuHo, errorProvider1, "Xã/ Phường chủ hộ");
                isValid &= Validations_Infragistics.ValidateChoose(cboQuanHuyenChuHo, errorProvider1, "Quận/ Huyện chủ hộ");
                isValid &= Validations_Infragistics.ValidateChoose(cboThanhPhoChuHo, errorProvider1, "Tỉnh/ Thành phố chủ hộ");

                //isValid &= Validations_Infragistics.ValidateChoose(cboNamSinh, errorProvider1, "Năm sinh");
                //Nam sinh
                string msgErr = "Chưa chọn thông tin '" + "Năm sinh" + "'.";

                errorProvider1.SetError(cboNamSinh, "");
                if (cboNamSinh.Text.Trim().Length == 0
                    || (cboNamSinh.SelectedIndex == 0 && cboNamSinh.Text.Contains("-")))
                {
                    isValid = false;
                    errorProvider1.SetError(cboNamSinh, msgErr);
                    cboNamSinh.Focus();
                }
                isValid &= Validations_Infragistics.ValidateChoose(cboThangSinh, errorProvider1, "Tháng sinh");
                isValid &= Validations_Infragistics.ValidateChoose(cboNgaySinh, errorProvider1, "Ngày sinh");
                isValid &= Validations_Infragistics.ValidateNull(txtTen, errorProvider1, "Tên chủ hộ");
                isValid &= Validations_Infragistics.ValidateNull(txtHoLot, errorProvider1, "Họ chủ hộ");

                if (isValid)
                {
                    bool isDouble = false;
                    string where = "SoSoHoKhau = " + txtSoSoHK.Text.Trim();
                    //Kiem tra trung so so ho khau trong cung 1 ho khau
                    //1.Truong hop them moi
                    //New
                    if (ObjHoKhau != null && ObjHoKhau.ID == 0)
                        isDouble = HoKhau.SelectCollectionDynamic(where, "").Count > 0;
                    //Edit
                    else if (ObjHoKhau != null && ObjHoKhau.ID != 0)
                    {
                        if (ObjHoKhau.SoSoHoKhau.ToString() != txtSoSoHK.Text.Trim())
                            isDouble = BLL.HoKhau.SelectCollectionDynamic(where, "").Count > 0;
                        else
                            isDouble = BLL.HoKhau.SelectCollectionDynamic(where, "").Count > 1;
                    }

                    if (isDouble)
                    {
                        MessageBox.Show("Đã có Số sổ hộ khẩu '" + txtSoSoHK.Text.Trim() + "' này trong danh sách.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtSoSoHK.Focus();
                        isValid = false;
                    }
                }
            }
            catch (Exception ex) { Logger.LocalLogger.Instance().WriteMessage(ex); }

            return isValid;
        }

        private void cboThanhPho_ValueChanged(object sender, EventArgs e)
        {
            if (cboThanhPho.Value != null)
            {
                int cboThanhPhoValue = 0;
                Int32.TryParse(cboThanhPho.Value.ToString(), out cboThanhPhoValue);
                if (cboThanhPhoValue > 0)
                    Global.setDataToComboQuanHuyen(cboQuanHuyen, Convert.ToInt32(cboThanhPho.Value));
            }
        }
        private void cboQuanHuyen_ValueChanged(object sender, EventArgs e)
        {
            if (cboQuanHuyen.Value != null)
            {
                int cboQuanHuyenValue = 0;
                Int32.TryParse(cboQuanHuyen.Value.ToString(), out cboQuanHuyenValue);
                if (cboQuanHuyenValue > 0)
                    Global.setDataToComboXaPhuong(cboXaPhuong, Convert.ToInt32(cboQuanHuyen.Value));
            }
        }
        private void cboXaPhuong_ValueChanged(object sender, EventArgs e)
        {
            if (cboXaPhuong.Value != null)
            {
                int cboXaPhuongValue = 0;
                Int32.TryParse(cboXaPhuong.Value.ToString(), out cboXaPhuongValue);
                if (cboXaPhuongValue > 0)
                    Global.setDataToComboToDanPho(cboToDanPho, Convert.ToInt32(cboXaPhuong.Value));
            }
        }

        private void cboThanhPhoChuHo_ValueChanged(object sender, EventArgs e)
        {
            if (cboThanhPhoChuHo.Value != null)
            {
                int cboThanhPhoValue = 0;
                Int32.TryParse(cboThanhPhoChuHo.Value.ToString(), out cboThanhPhoValue);
                if (cboThanhPhoValue > 0)
                    Global.setDataToComboQuanHuyen(cboQuanHuyenChuHo, Convert.ToInt32(cboThanhPhoChuHo.Value));
            }
        }
        private void cboQuanHuyenChuHo_ValueChanged(object sender, EventArgs e)
        {
            if (cboQuanHuyenChuHo.Value != null)
            {
                int cboQuanHuyenValue = 0;
                Int32.TryParse(cboQuanHuyenChuHo.Value.ToString(), out cboQuanHuyenValue);
                if (cboQuanHuyenValue > 0)
                    Global.setDataToComboXaPhuong(cboXaPhuongChuHo, Convert.ToInt32(cboQuanHuyenChuHo.Value));
            }
        }
        private void cboXaPhuongChuHo_ValueChanged(object sender, EventArgs e)
        {
            if (cboXaPhuongChuHo.Value != null)
            {
                int cboXaPhuongValue = 0;
                Int32.TryParse(cboXaPhuongChuHo.Value.ToString(), out cboXaPhuongValue);
                if (cboXaPhuongValue > 0)
                    Global.setDataToComboToDanPho(cboToDanPhoChuHo, Convert.ToInt32(cboXaPhuongChuHo.Value));
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                //Cap nhat gia tri
                if (!GetData())
                    return;

                if (ObjHoKhau.ID > 0)
                    ObjHoKhau.Update();
                else
                    ObjHoKhau.Insert();

                //Luu thong tin chu ho cua ho khau
                TaoThongTinChuHo();

                //Load danh sách nhan khau
                LoadDataDanhSachNhanKhau(ObjHoKhau.ID);

                MessageBox.Show("Đã lưu thành công", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show("Lỗi trong quá trình xử lý: " + ex.Message);
            }
            finally { Cursor = Cursors.Default; }
        }
        private void btnDong_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region Danh sach nhan khau
        //VALIDATE
        private DataSet dsDanhSachNhanKhau = new DataSet();
        private DataTable dtDanhSachNhanKhau;

        private void LoadDataDanhSachNhanKhau(int hoKhauID)
        {
            try
            {
                dsDanhSachNhanKhau = HoKhau.DanhSachNhanKhau(hoKhauID);
                dtDanhSachNhanKhau = dsDanhSachNhanKhau.Tables[0];

                gridNhanKhau.DataSource = dtDanhSachNhanKhau;
            }
            catch (Exception ex) { Logger.LocalLogger.Instance().WriteMessage(ex); }
        }

        //ULTRAGRID
        private void gridNhanKhau_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            try
            {
                e.Layout.Override.CellClickAction = CellClickAction.RowSelect;

                UltraGridBand band = e.Layout.Bands[0];

                band.Columns["ID"].Hidden = true;
                band.Columns["MaNhanKhau"].Header.Caption = "Mã nhân khẩu";
                band.Columns["TinhTrang"].ValueList = Global.getValueListTinhTrang();
                band.Columns["TinhTrang"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
                band.Columns["GioiTinh"].ValueList = Global.getValueListGioiTinh();
                band.Columns["GioiTinh"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
            }
            catch (Exception ex) { Logger.LocalLogger.Instance().WriteMessage(ex); }
        }
        private void gridNhanKhau_DoubleClickRow(object sender, DoubleClickRowEventArgs e)
        {
            EditNhanKhau();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (ObjHoKhau == null || ObjHoKhau.ID == 0)
            {
                MessageBox.Show("Thông tin Hộ khẩu phải được nhập và lưu trước khi thêm mới 1 nhân khẩu", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //Open form to edit
            frmThemMoiNhanKhau frm = new frmThemMoiNhanKhau();
            frm.HoKhauID = ObjHoKhau.ID;
            frm.ShowDialog();

            //Update row add on grid
            LoadDataDanhSachNhanKhau(ObjHoKhau.ID);
        }
        private void btnEdit_Click(object sender, EventArgs e)
        {
            EditNhanKhau();
        }
        private void btnDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (ObjHoKhau == null || ObjHoKhau.ID == 0)
                    return;

                Cursor = Cursors.WaitCursor;

                if (gridNhanKhau.ActiveRow != null && gridNhanKhau.ActiveRow.Cells["ID"].Value != null)
                {
                    //Get ID nhan khau
                    int nkID = System.Convert.ToInt32(gridNhanKhau.ActiveRow.Cells["ID"].Value);
                    NhanKhau delNK = NhanKhau.Load(nkID);
                    string hoTen = delNK.HoLot + " " + delNK.Ten;

                    //Truong hop khong co nha khau nao:
                    if (DialogResult.OK == MessageBox.Show("Bạn có chắc chắn muốn xóa thông tin nhân khẩu '" + hoTen + "' này không?.", this.Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    {
                        //Xoa thong tin nhan khau chi tiet truoc khi xoa thong tin nha khau
                        NhanKhau_HinhAnh.DeleteBy_NhanKhauID(nkID);
                        NhanKhau_QuanHeGiaDinh.DeleteBy_NhanKhauID(nkID);
                        NhanKhau_QuaTrinh.DeleteBy_NhanKhauID(nkID);
                        NhanKhau_TomTatBanThan.DeleteBy_NhanKhauID(nkID);

                        NhanKhau.DeleteNhanKhau(nkID);

                        MessageBox.Show("Đã xóa thành công thông tin nhân khẩu '" + hoTen + "'.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                    LoadDataDanhSachNhanKhau(ObjHoKhau.ID);
                }
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show(ex.Message);
            }
            finally { Cursor = Cursors.Default; }
        }
        private void ddbChuyenDi_Click(object sender, EventArgs e)
        {
            ChuyenNhanKhau(true);
        }
        private void btnCatKhau_Click(object sender, EventArgs e)
        {
            ChuyenNhanKhau(false);
        }
        private void btnChuyenDoiTuong_Click(object sender, EventArgs e)
        {
            try
            {
                if (ObjHoKhau == null || ObjHoKhau.ID == 0)
                    return;

                Cursor = Cursors.WaitCursor;

                if (gridNhanKhau.ActiveRow != null && gridNhanKhau.ActiveRow.Cells["ID"].Value != null)
                {
                    //Get ID nhan khau
                    int nkID = System.Convert.ToInt32(gridNhanKhau.ActiveRow.Cells["ID"].Value);
                    NhanKhau editNK = NhanKhau.Load(nkID);

                    DoiTuong objDoiTuong = new DoiTuong();
                    Global.SaoChep(editNK, objDoiTuong);
                    objDoiTuong.ID = 0;

                    FrmThemMoiDoiTuong frm = new FrmThemMoiDoiTuong();
                    frm.ObjDoiTuong = objDoiTuong;
                    frm.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show(ex.Message);
            }
            finally { Cursor = Cursors.Default; }
        }
        private void EditNhanKhau()
        {
            try
            {
                if (ObjHoKhau == null || ObjHoKhau.ID == 0)
                    return;

                Cursor = Cursors.WaitCursor;

                if (gridNhanKhau.ActiveRow != null && gridNhanKhau.ActiveRow.Cells["ID"].Value != null)
                {
                    //Get ID nhan khau
                    int nkID = System.Convert.ToInt32(gridNhanKhau.ActiveRow.Cells["ID"].Value);
                    NhanKhau editNK = NhanKhau.Load(nkID);

                    //Open form to edit
                    frmThemMoiNhanKhau frm = new frmThemMoiNhanKhau();
                    frm.ObjNhanKhau = editNK;
                    frm.ShowDialog();

                    //Update row add on grid
                    LoadDataDanhSachNhanKhau(ObjHoKhau.ID);
                }
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show(ex.Message);
            }
            finally { Cursor = Cursors.Default; }
        }
        private void ChuyenNhanKhau(bool isChuyenNhanKhau)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                if (ObjHoKhau == null || ObjHoKhau.ID == 0)
                    return;

                if (gridNhanKhau.ActiveRow != null && gridNhanKhau.ActiveRow.Cells["ID"].Value != null)
                {
                    //Get ID nhan khau
                    int nkID = System.Convert.ToInt32(gridNhanKhau.ActiveRow.Cells["ID"].Value);

                    FrmChuyenNhanKhau frm = new FrmChuyenNhanKhau();
                    frm.IsChuyenNhanKhau = isChuyenNhanKhau;
                    frm.IDNhanKhau = nkID;
                    frm.ShowDialog();

                    LoadDataDanhSachNhanKhau(ObjHoKhau.ID);
                }
            }
            catch (Exception ex)
            {
                Logger.LocalLogger.Instance().WriteMessage(ex);
                MessageBox.Show(ex.Message);
            }
            finally { Cursor = Cursors.Default; }
        }
        #endregion

    }
}
